/**!
 * index.js
 * Copyright(c) 2018 Tenny
 * MIT Licensed
 */
const log4js = require('log4js');

// 需要忽略的请求日志
let ext = ['js', 'css', 'jpg', 'png', 'html', 'ico', 'map'];
let logger = log4js.getLogger('app');

class LogAdapter {

  constructor(filename) {
    log4js.configure({
      appenders: {
        console: { type: 'console' }, // console.log 日志
        file: { type: 'dateFile', filename: `/tmp/${filename}.log`, keepFileExt: true },
        'just-file': {type: 'logLevelFilter', appender: 'file', level: 'info'}
      },
      categories: { default: { appenders: ['console', 'just-file'], level: 'debug' } }
    });
  }

  adapt() {
    return async (ctx, next) => {
      let url = ctx.url;
      const start = Date.now(); // 接口请求开始时间
      await next();
      const ms = Date.now() - start;
      let urlExt = url.substring(url.lastIndexOf('.') + 1); // 请求的文件后缀
      if(ext.includes(urlExt) === false) { // 需要忽略的请求后缀不包含该请求，正常打印日志
        logger.info(`${ctx.method} ${url} ${ctx.status} ${ms}ms`);
      } else { // 该请求包含在忽略列表
        if(ctx.status !== 200 && ctx.status !== 304) { // 请求失败，正常打印日志
          logger.warn(`${ctx.method} ${url} ${ctx.status} ${ms}ms`);
        }
      }
    }
  }
}

module.exports = LogAdapter;
